<template>
  <div ref="bbxBaseLayoutContainer" class="bbx-base-tile-tab-bar-box">
    <div id="bbx-base-tile-tab-list" class="bbx-base-tab-list">

      <div
        ref="listItem"
        class="bbx-base-tab-list-item"
        @click="changeItem(item, index)"
        :class="[nowItem == item.tabName ? 'is-select' : '']"
        v-show="item.tabShow"
        v-for="(item, index) in visibleTabs"
        :key="item.tabName">
        <span class="overHideCon-1">{{ item.tabLabel }}</span>
      </div>

      <el-dropdown 
        v-show="showDropdown"
        placement="top-start"
        trigger="click"
        :hide-on-click="false"
        @command="handleCommand">
        <span :class="['layout-dropdown-link', dropdownActive && 'is-active']">
          <span class="layout-link-text">{{ dropdownActive }}</span> 
          <span class="layout-link-bg">
            <i class="el-icon-caret-bottom el-icon--right"></i>
          </span>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <div class="search">
              <el-input
                placeholder="搜索页签"
                suffix-icon="el-icon-search"
                v-model="keyword"
                @input="searchTab">
              </el-input>
            </div>
          </el-dropdown-item>
          <div class="layout-dropdown-content">
            <template v-if="dropdownTabs.length">
              <el-dropdown-item
                v-for="tab in dropdownTabs"
                :key="tab.tabName"
                :command="tab"
              >
                {{ tab.tabLabel }}
              </el-dropdown-item>
            </template>
            <div v-else class="layout-dropdown-empty"> 
              暂无数据
            </div>
          </div>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    
    <div 
      v-if="isFormMultiRow"
      class="bbx-base-tab-bar-layout-icon"
      @click="openLayoutModal">
      <i class="iconfont icon-buju"></i>
    </div>
  </div>
</template>

<script>
import { getRootWindow } from '@src/util/dom'
import { cloneDeep, debounce } from 'lodash'
import { formWithMultipleColumnsStashKey } from '@src/modules/system/frame/store'
export default {
  props: {
    barList: {
      type: Array,
      default: () => ([])
    },
    nowItem: {
      type: [String, null],
      default: null
    },
    trackConfig: {
      type: Object,
      default: () => ({})
    },
    module: {
      type: String,
      default: ''
    },
    structure: {
      type: Number,
      default: 1
    }
  },
  watch: {
    'barList': {
      handler (data) {
        if(data.length && this.structure === 1) {
          this.$nextTick(() => {
            this.initCalculateTabs();
          })
        } else {
          this.visibleTabs = data || [];
        }
      },
      deep: true,
      immediate: true,
    },
    nowItem: {
      handler(newVal) {
        this.checkNowItem(newVal)
      },
      immediate: true
    }
  },
  data () {
    return {
      keyword: '',
      isSearch: false,
      dropdownActiveLabel: '', // 选中下拉项
      dropdownActiveValue: '',
      visibleTabs: [], // 存储可见的tab
      dropdownTabs: [], // 存储下拉列表中的tab
      storeVisibleTabs: [], // 备份可见列表数据
      storeDropdownTabs: [], // 备份下拉列表数据
      containerWidth: 0, // tab存储容器的总宽度
      totalTabWidth: 0, // 存储tab宽度
      tabPaddingWidth: 48, // 每个tab的padding
      dropdownIconWidth: 28, // 下拉icon宽度
      dropdownActiveLabelWidth: 16, // 选中下拉文本长度 初始值包含padding
      isFontSize: '14px Arial', // 字体大小
      canvasContext: null, // 生成一个canvas用于获取文本宽度 不用操作dom
    }
  },
  computed: {
    isFormMultiRow() {
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.FORM_MULTI_ROW
    },
    dropdownActive() {
      return this.dropdownActiveLabel || '';
    },
    showDropdown() {
      return (this.structure === 1 && this.dropdownTabs?.length) || this.isSearch;
    }
  },
  methods: {
    openLayoutModal() {
      this.$emit('openLayoutModal')
    },
    changeItem (item, index) {
      if(this.structure === 1) {
        this.dropdownActiveLabel = '';
        // 切换显示区域时 就重置为备份数据
        this.visibleTabs = this.storeVisibleTabs;
        this.dropdownTabs = this.storeDropdownTabs;
      }

      this.$emit('changeItem', item)
      // this.$refs.listItem[index].scrollIntoView({ behavior: 'instant' })
      item.needTrack && this.$track.clickStat(this.$track.formatParams('DETAIL_ADD_ONS_TABS', item[this.labelKey]));
    },
    searchTab(keyword) {
      this.isSearch = true;
      if(!keyword) {
        this.dropdownTabs = this.storeDropdownTabs;
      }
      this.dropdownTabs = this.dropdownTabs.filter(item => {
        return item.tabLabel.includes(keyword);
      });
    },
    handleCommand(command) {
      if(!command) return
      this.dropdownActiveLabel = command.tabLabel || '';
      this.dropdownActiveValue = command.tabName;
      this.$emit('changeItem', command)

      // 加入下拉tab后 重新计算宽度
      this.calculateVisibleTabs()
    },
    init() {
      this.totalTabWidth = 0;
      this.dropdownActiveLabelWidth = this.tabPaddingWidth;
      this.visibleTabs = [];
      this.dropdownTabs = [];
    },
    /**
		 * @des 检查当前选项是否在list中
		 */
		 checkNowItem(checked){
      this.barList.map(item=>{
        if(item['tabName'] === checked){
          item['tabShow'] = true;
        }
        return item;
      })
    },
    /**
		 * @des 获取文本宽度
		 */
    measureTextWidth(text, font) {
      this.canvasContext.font = font;

      // 测量文本的宽度
      const metrics = this.canvasContext.measureText(text);

      // 返回测量的宽度 48是padding
      return Number(metrics.width.toFixed(2)) + this.tabPaddingWidth;
    },
    /**
		 * @des 计算分割tab数据
		 */
    calculateVisibleTabs(isResize) {
      this.init()

      // 计算下拉选中项宽度 总宽度要加上下拉选中tab的宽度
      if(this.dropdownActiveLabel) {
        this.dropdownActiveLabelWidth += this.measureTextWidth(this.dropdownActiveLabel, this.isFontSize);
      }

      // 计算初始宽度
      this.totalTabWidth = this.tabPaddingWidth + this.dropdownIconWidth + this.dropdownActiveLabelWidth;

      this.barList.forEach(tab => {
				
        this.totalTabWidth += this.measureTextWidth(tab.tabLabel, this.isFontSize);

        // 已选tab 因屏幕变小 被隐藏了 把已选tab赋值给下拉默认选中
        const nowItemIndex = this.dropdownTabs.findIndex(item => item.tabName === this.nowItem);
        if(isResize && nowItemIndex > -1) {
          this.dropdownActiveLabel = this.dropdownTabs[nowItemIndex].tabLabel;
          this.totalTabWidth += this.measureTextWidth(this.dropdownTabs[nowItemIndex].tabLabel, this.isFontSize);
        }

        // 切换下拉后 如果当前项已选tab进入visibleTabs 则清空dropdownActiveLabel
        if(this.visibleTabs.findIndex(item => item.tabName === this.dropdownActiveValue) > -1) {
          this.dropdownActiveLabel = '';
        }

        if (this.totalTabWidth < this.containerWidth) {
          this.visibleTabs.push(tab);
        } else {
          this.dropdownTabs.push(tab);
        }
      });

      // 存在关键字 只展示关键字相关数据
      if(this.keyword) {
        this.dropdownTabs = this.dropdownTabs.filter(item => {
          return item.tabLabel.includes(this.keyword)
        });
      }

      // 显示区域切换时 就重置为备份数据 每次都重新计算有点影响性能
      if(!this.storeVisibleTabs.length || !this.storeDropdownTabs.length || isResize) {
        this.storeVisibleTabs = cloneDeep(this.visibleTabs);
      	this.storeDropdownTabs = cloneDeep(this.dropdownTabs);
      }      
    },
    initCalculateTabs(isResize) {
      this.containerWidth = this.$refs?.bbxBaseLayoutContainer?.offsetWidth || 0;
      this.calculateVisibleTabs(isResize);
    },
    getLayoutTabBarWidth() {
      if(this.containerWidth === 0) {
        window.dispatchEvent(new Event('resize'));
      }
    }
  },
  mounted() {
      // 创建并复用canvas元素和上下文
      const canvas = document.createElement('canvas');
      this.canvasContext = canvas.getContext('2d');
      if(this.structure === 1) {
        this.initCalculateTabs();
        window.addEventListener('resize', debounce(() => this.initCalculateTabs('resize'), 200));
        const RootWindow = getRootWindow(window);
        RootWindow.getLayoutTabBarWidth = this.getLayoutTabBarWidth;
      }
      if(this.isFormMultiRow){
        setTimeout(()=>{
            const rootWindow = getRootWindow(window)
            rootWindow?.activeGuide(formWithMultipleColumnsStashKey)
          }, 2000)
      }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.initCalculateTabs);
  }
}
</script>
<style lang="scss" scoped>
$tab-item-height: 40px;
.bbx-base-tile-tab-bar-box {
	position: sticky;
	top: 0;
	display: flex;
	width: 100%;
	align-items: baseline;
	box-sizing: border-box;
	z-index: 35;
	background-color: #fff;

	&::after {
		content: '';
		width: 100%;
		border-bottom: 1px solid #E4E7ED;
		position: absolute;
		bottom: 0;
		left: 0;
		z-index: 99;
	}

	.bbx-base-tab-list {
		display: flex;
		align-items: center;
		flex: 1;
		flex-wrap: wrap;
		height: $tab-item-height;

		.bbx-base-tab-list-item {
			flex-wrap: wrap;
			max-width: 100%;
			margin: 0 24px;
			height: $tab-item-height;
			line-height: $tab-item-height;
			position: relative;
			cursor: pointer;
		}

		.is-select {
			color:$color-primary;
			&::after {
				content: '';
				width: 100%;
				height: 2px;
				background-color: $color-primary;
				position: absolute;
				bottom: 0;
				left: 0;
				z-index: 101;
			}
		}

	}
}
</style>
<style lang="scss">
.bbx-base-tile-tab-bar-box {
	.bbx-base-tab-bar-layout-icon {
		padding: 10px;
		cursor: pointer;
	}
	.layout-dropdown-link {
		position: relative;
		display: inline-block;
		box-sizing: border-box;
    height: 40px;
		line-height: 40px;
    padding: 0 8px;
		.layout-link-text {
			cursor: pointer;
		}
		.layout-link-bg {
			display: inline-block;
			width: 24px;
			height: 24px;
			line-height: 24px;
			border-radius: 4px;
			margin-left: 4px;
			background-color: #EBEDF0;
			&:hover {
				color: $color-primary-light-6;
				cursor: pointer;
			}
		}
	}
	
	.is-active {
		color: $color-primary;
		&::after {
			content: '';
			width: 100%;
			height: 2px;
			background-color: $color-primary;
			position: absolute;
			bottom: 0;
			left: 0;
			z-index: 101;
		}
	}
}
.layout-dropdown-content {
  max-height: 500px;
  overflow-y: auto;
}
.el-dropdown-menu--small .el-dropdown-menu__item {
	padding: 0 12px;
	color: #8C8C8C;
	line-height: 36px;
	width: 240px;
	.search {
		margin-bottom: 4px;
	}
}
.layout-dropdown-empty {
	padding: 4px 10px;
	text-align: center;
	color: #8C8C8C;
	font-size: 12px;
}
</style>